import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.List;


public class Missile {
	public static final int X_SPEED = 20;
	public static final int Y_SPEED = 20;
	public static final int WIDTH = 10;
	public static final int HEIGHT = 10;
	
	private TankClient  tc = null;
	private boolean live = true;
	private boolean good = false;
	
	public boolean isGood() {
		return good;
	}
	
	public void setLive(boolean live) {
		this.live = live;
	}

	private int x,y;
	Tank.Direction dir = null;
	
	
	public Missile(int x,int y,Tank.Direction dir)
	{
		this.x = x;
		this.y = y;
		this.dir = dir;
	}
	public Missile(int x,int y,boolean good,Tank.Direction dir,TankClient tc)
	{
		this(x,y,dir);
		this.good = good;
		this.tc = tc;
		
	}
	
	public boolean isLive()
	{
		return live;
	}
	
	public void draw(Graphics g)
	{
		if (!live) {
			this.tc.missiles.remove(this);
			return;
		}
		Color c = g.getColor();
		if (good) {
			g.setColor(Color.GRAY);
		}
		else{	
			g.setColor(Color.BLACK);
		}
		g.fillOval(x, y, WIDTH, HEIGHT);
		g.setColor(c);
		move();
	}
	
	public void move()
	{
		switch (dir) {
		case UP:
			y -= Y_SPEED;
			break;
		case R_UP:
			x += X_SPEED;
			y -= Y_SPEED;
			break;
		case RIGHT:
			x += X_SPEED;
			break;
		case R_DOWN:
			x += X_SPEED;
			y += Y_SPEED;
			break;
		case DOWN:
			y += Y_SPEED;
			break;
		case L_DOWN:
			x -= X_SPEED;
			y += Y_SPEED;
			break;
		case LEFT:
			x -= X_SPEED;
			break;
		case L_UP:
			x -= X_SPEED;
			y -= Y_SPEED;
			break;
		}
		if(x < 0 || y < 0 || x > TankClient.GAME_WIDTH || y >TankClient.GAME_HEIGHT)
		{
			live = false;
			
		}
	}
	
	public Rectangle getRec()
	{
		return new Rectangle(x,y,WIDTH,HEIGHT);
	}
	
	public boolean hitTank(Tank t)
	{
		if (isLive()&&this.getRec().intersects(t.getRec())&& t.isLive()&&(this.good != t.isGood())) {
			if (this.good != true) {
				t.setLife(t.getLife() - 20);
				if (t.getLife() <= 0) {
					t.setLive(false);
				}
			}else {
				t.setLive(false);
			}
			
			this.setLive(false);
			Explode e = new Explode(this.x,this.y,tc);
			tc.explodes.add(e);
			return true;
		}
		return false;
		
	}
	
	public boolean hitTanks(List<Tank> tanks)
	{
		for (int i = 0; i < tanks.size(); i++) {
			if (hitTank(tanks.get(i))) {
				return true;
			}
		}
		return false;
		
	}
	
	public boolean collidesWithWall (Wall w) {
		if (this.getRec().intersects(w.getRec())) {
			this.live = false;
			return true;
		}
		return false;
		
	}
}
